/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
    Component,
} from 'react';

import {
  StyleSheet,
  Text,
  TextInput,
  View,
  Image,
  Alert,
  TouchableHighlight,
  Modal,
  ImageStore 
} from 'react-native';

import {Actions,ActionConst} from 'react-native-router-flux';
import CommonUtils from '../utils/common';
import CommonStyles from '../styles/common';
import Colors from '../styles/colors';
import LoadingView from '../components/loadingView';
import Toast from '../utils/toast';
import Ionicons  from 'react-native-vector-icons/Ionicons';
import CameraRollPicker from 'react-native-camera-roll-picker';
import ImageResizer from 'react-native-image-resizer';

import {ActionSheet,Button,WhiteSpace,WingBlank} from 'antd-mobile';

import {ScanBarCodeClean,ChangeInputOrderId} from '../actions/app';

export default class ImageUpload extends Component {
    constructor (props) {
        super(props)
        this.state={
            modalVisible:false,
            selectedImages:[],
            imageSource:null,
            imageBase64:'',//操作后不能清空
            isUploading:false,
        };
        this.onPressImagesSelect = this.onPressImagesSelect.bind(this);
        this.onPressSelect = this.onPressSelect.bind(this);
        this.onPressUpload = this.onPressUpload.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.imageBase64&&nextProps.imageBase64!=this.state.imageBase64) {
            const source = {uri:'data:image;base64,'+nextProps.imageBase64,isStatic:true};
            this.setState({imageSource: source,imageBase64:nextProps.imageBase64});
        }
    }

    onPressSelect(){
        const btns = ['拍照','相册选择','取消'];
        ActionSheet.showActionSheetWithOptions({
            options: btns,
            cancelButtonIndex: btns.length- 1,
            message: '选择照片',
            maskClosable: true,
        },
        (buttonIndex) => {
            if(buttonIndex==0){
                Actions.takePhoto();
            }
            else if(buttonIndex==1){
                this.setState({selectedImages:[]});
                this.setModalVisible(true);
            }
        });
    }

    async onPressUpload(){
        if(this.state.imageSource==null){
            Toast.showShort('请先选择图片');
            return;
        }
        this.setState({isUploading:true});
        //上传图片base64
        //ImageUpload(base64)
        await CommonUtils.sleep(3000);
        Toast.showShort('上传图片成功');
        this.setState({isUploading:false,imageSource:null});
    }

    setModalVisible(flag){
        this.setState({modalVisible:flag});
    }

    getSelectedImages(images, current) {
        this.setState({selectedImages:images});
    }

    resizeImage(uri){
        ImageResizer.createResizedImage(uri, 480, 640, 'JPEG', 100, 0, null).then((resizedImageUri) => {
            ImageStore.getBase64ForTag(resizedImageUri,(data)=>{
                const source = {uri:resizedImageUri,isStatic:true};
                this.setState({imageSource:source,imageBase64:data});
            },(error)=>{
                Toast.showShort(error.message);
            });
        }).catch((err) => {
            Toast.showShort(err.message);
        });
    }

    onPressImagesSelect(){
        if(this.state.selectedImages.length>0){
            this.resizeImage(this.state.selectedImages[0].uri);
        }
        this.setModalVisible(false);
    }

    render() {
        if (this.state.isUploading){
            return (<LoadingView isLoading={this.state.isUploading} tip='上传中...'/>);
        }

        return (
            <View style={[CommonStyles.container,CommonStyles.padding10]}>
                <Modal
                    animationType={'fade'}
                    transparent={true}
                    visible={this.state.modalVisible}
                    onRequestClose={() => {this.setModalVisible(false)}}
                    >
                    <View style={[CommonStyles.container,CommonStyles.flexHCenter,styles.modalContainer]}>
                        <CameraRollPicker 
                            selected={this.state.selectedImages} 
                            assetType='Photos'
                            maximum={1} 
                            callback={(images, current)=>this.getSelectedImages(images, current)} 
                            selectedMarker={
                                <Ionicons name="md-checkmark-circle" size={24} style={styles.checkmark}></Ionicons>
                            }/>
                        <WingBlank size="md">
                            <Button onClick={this.onPressImagesSelect}>确  定</Button>
                            <WhiteSpace size='md' />
                        </WingBlank>
                    </View>
                </Modal>
                <View style={styles.uploadContainer}>
                    <Button onClick={this.onPressSelect}>选择图片</Button>
                    {this.state.imageSource!=null?(
                        <View style={CommonStyles.flex1}>
                            <View style={styles.imgContainer}>
                                <View style={styles.imgContent}>
                                    <Image source={this.state.imageSource} style={styles.imgShow} />
                                </View>
                            </View>
                            <WhiteSpace size='xl' />
                            <Button type='primary' onClick={this.onPressUpload}>上传图片</Button>
                        </View>
                        ):null}
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    modalContainer:{
        backgroundColor:'#fff',
        opacity:0.9
    },
    checkmark:{
        color:Colors.default_theme,
        position: 'absolute',
        top: 5,
        right: 5,
        backgroundColor: 'transparent',
    },
    uploadContainer:{
        flex:1,
        flexDirection: 'column',
    },
    hiddenContainer:{
        flex:1,
        flexDirection: 'column',
    },
    imgContainer:{
        height:240,
        alignItems:'center',
    },
    imgContent:{
        marginTop:10,
        width:180,
        height:240,
        borderWidth:1,
        borderColor:'#ddd'
    },
    imgShow:{
        width:180,
        height:240,
        resizeMode:'contain'
    }
});

